const aliSdk = require("../../utils/aliIot-sdk.js")
const app = getApp()
let debounceTimer = null // 定义防抖定时器

Page({

  /**
   * 页面的初始数据
   */
  data: {
    levels: ['1档', '2档', '3档'], // 档位选项
    currentLevel: '3档', // 初始档位为0
    product_type: '', //产品类型
    deviceName: '',
    // 只读取的参数
    local_dev_status: '- -',//手机端设备运行状态
    // 盐疗参数
    salt_concentration: 0,//盐浓度
    salt_timing: 0,//盐疗定时
    temperature: 0,//温度档位
    salt_add_time: 0,//盐疗定时初始值
    //氧疗参数
    oxygen_flow: 0,//氧流量
    oxygen_dtime: 0,// 制氧定时界面显示
    oxygen_dtime_show: 0,// 制氧定时最大值
    currentX: 10,
    isDecrementToDash: false,  // 标记是否因减小操作显示--
    isIncrementToDash: false,   // 标记是否因增加操作显示--
    oxygen_time: "- -",//制氧运行时间
    total_time: "- -",//盐疗累计运行时间
    oxygen_concentration: "0",//氧浓度
    oxtotal_time: 0,//制氧累计时间
    key_flag: 0,//按键标志 1/2/3分别表示电源、盐疗、氧疗
    //公共参数
    err_code: 0,
    powerSwitch: 0,//控制开关
    dev_status: 0,//0/1/2/3分别表示设备关闭，设备开启、盐疗开启、氧疗开启

    screen_off: 0,//亮度档位
    dark_mode: 0,//夜间模式
    //开关按钮
    states: ['关机', '开机', '启动'],
    currentIndex: 0,
    buttonText: '关机',

    //开关状态
    states_png: ['end.png', 'start.png', 'run.png'],
    currentIndex_png: 0,
    buttonText_png: 'end.png',
    // 产品类型
    mode_type: 0,
    //不同型号设备最大参数
    salt_concentration_max: 0, //盐浓度最大
    salt_timing_max: 0,//盐疗定时最大时长
    selected: null, //模式选中按钮颜色
    show_usd: true,



    salt_button1: false,
    salt_canClick: true,
    ox_button2: false,
    ox_canClick: true,
    //定时器---

    timer: null,
    //定时器---

    mof_powewr: 0,

    active: 0,
    "list": [
      {
        "pagePath": "/pages/mof/mof",
        "iconPath": "/pages/img/home_off.png",
        "selectedIconPath": "/pages/img/home_on.png",
        "text": "首页"
      },
      {
        "pagePath": "/pages/wifi/wifi",
        "iconPath": "/pages/img/wifi_off.png",
        "selectedIconPath": "/pages/img/wifi_on.png",
        "text": "配网"
      },
      {
        "pagePath": "/pages/user/user",
        "iconPath": "/pages/img/user_off.png",
        "selectedIconPath": "/pages/img/user_on.png",
        "text": "用户"
      }
    ]

  },

  onChange(e) {
    let path = e.currentTarget.dataset.path;
    let index = e.currentTarget.dataset.index;
    this.setData({
      active: index
    })
    wx.switchTab({
      url: path,
    })
  },

  /**
   * 默认首页产品图
   */
  previewImage: function () {
    wx.previewImage({
      current: '../img/salt.png', // 当前显示图片的链接
      urls: ['https://gitee.com/tpyszc/tpyszc_image/raw/master/salt.png', 'https://gitee.com/tpyszc/tpyszc_image/raw/master/xns.png'] // 需要预览的图片链接列表
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    const that = this;
    that.get_devname_product_type();

  },

  /**
   * 缓存中获取设备编号+产品类型
   */
  get_devname_product_type: function () {
    const that = this;
    const deviceName = wx.getStorageSync('deviceName'); // 从本地获取值
    const product_type = wx.getStorageSync('product_type');
    const mode_type = wx.getStorageSync('mode_type');
    if (mode_type == 90 || mode_type == 95) {
      that.setData({
        deviceName: deviceName,
        product_type: product_type,
        mode_type: mode_type,
        salt_concentration_max: 10, //盐浓度最大
        salt_timing_max: 90,//盐疗定时最大时长
        oxygen_dtime_show: 120//氧疗定时最大时长
      })
    }
    if (mode_type == 91 || mode_type == 96) {
      that.setData({
        deviceName: deviceName,
        product_type: product_type,
        mode_type: mode_type,
        salt_concentration_max: 15, //盐浓度最大
        salt_timing_max: 60,//盐疗定时最大时长
        oxygen_dtime_show: 120//氧疗定时最大时长
      })
    }
    if (mode_type == 94 || mode_type == 99) {
      that.setData({
        deviceName: deviceName,
        product_type: product_type,
        mode_type: mode_type,
        salt_concentration_max: 30, //盐浓度最大
        salt_timing_max: 90,//盐疗定时最大时长
        oxygen_dtime_show: 480//氧疗定时最大时长
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染（获取设备编码+产品名称）
   */
  onReady() {
    const that = this;
    that.get_devname_product_type();

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this;
    that.get_devname_product_type();
    that.startAliyun();
  },

  /**
 * 默认参数
 */
  aliyun_default: function () {
    const that = this;
    // 停止治疗
    that.setData({
      currentIndex: 0,
      buttonText: that.data.states[0],
      currentIndex_png: 0,
      buttonText_png: that.data.states_png[0],
      total_time: "- -",//累计运行时间
      local_dev_status: "- -",//手机端设备运行状态
      dev_status: 0,//云端设备运行状态
      salt_concentration: "- -",//盐浓度
      salt_timing: "- -",//盐疗定时
      err_code: 0,//异常状态码
      currentLevel: '- -', // 更新当前档位
      temperature: "- -"//温度档位
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.stopAliyun();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  },

  /**
   * 弹框--打开设备提示
   * @param {*} e 
   */
  open_dev: function () {
    this.stopAliyun();
    wx.showToast({
      title: '请打开设备',
      duration: 1600,
      mask: true,
      image: '../img/end.png'
    });
  },

  /**
   * 自定义方法--数据转换
   * @param {*} 步进值 ±1/0.1 
   * @param {*} 字符转数字 
   * @param {*} 小数/整数 
   */
  button_int_number: function (number1, number2, number3) {
    if (number3 == 1) {
      const formatting_number = parseInt(number1) + parseInt(number2);
      return formatting_number;
    } else if (number3 == 2) {
      const formatting_number2 = parseFloat(number2);
      return number1 + formatting_number2;
    } else if (number3 == 3) {
      const result = parseInt(number1) - parseInt(number2);
      return result;
    } else {
      wx.showToast({
        title: '设备连接异常',
        icon: 'err',
        duration: 1500,
      });
    }
  },

  /**
   *弹框 -- 发送数据到云端成功
   * @param {*} e 
   */
  send_aliyun_iot() {
    wx.showToast({
      title: '发送成功',
      duration: 2000,
      mask: true,
      image: '../img/send_aliyun.png'
    });
  },



  /**
   * * 定时器开始--2秒一次调用云平台数据
   */
  startAliyun: function () {
    if (this.data.timer) {
      return
    }

    this.data.timer = setInterval(() => {
      this.loadData();
    }, 1500)
  },

  /**
 * * 定时器结束
 */
  stopAliyun: function () {
    if (this.data.timer) {
      clearInterval(this.data.timer)
      this.data.timer = null
    }
  },

  /**
 * 定时器停止
 */
  stopApiCall: function () {
    const that = this;
    // 清除定时器
    if (that.interval) {
      clearInterval(that.interval);
    }
  },


  /**
   * 根据不同的产品调用不同的解析方法
   * 西纳舒岩盐气溶胶治疗仪{a11uQJCzUPe}
   * 盐氧一体机{a1L4GogBzON}
   */
  loadData: function () {
    const that = this;
    aliSdk.request({
      Action: "QueryDevicePropertyStatus",
      ProductKey: that.data.product_type,
      DeviceName: that.data.deviceName
    }, {
      method: "POST"
    },
      (res) => {
        if (res.data.Success) {

          that.mof_setPropertyData(res.data.Data.List.PropertyStatusInfo);

        } else {
          wx.showToast({
            title: '设备连接失败',
            icon: 'error',
            duration: 1300,
          });
          that.stopAliyun();
        }
      },
      (res) => {
        // 默认都会执行
        // that.setPropertyData(res.data.Data.List.PropertyStatusInfo);
      }
    )
  },




  /**
 * 盐氧--获取阿里云端数据并更新页面数据
 */
  mof_setPropertyData: function (infos) {
    const that = this;
    // 盐氧一体机
    var propertys = that.convertPropertyStatusInfo(infos);
    that.setData({
      // 只读取的参数
      total_time: propertys.total_time,//累计运行时间
      screen_off: propertys.screen_off, //亮度模式
      dev_status: propertys.dev_status,//工作状态 0/1/2/3分别表示设备关闭，设备开启、盐疗开启、氧疗开启
      key_flag: propertys.key_flag,//按键标志 1/2/3分别表示电源、盐疗、氧疗
      temperature: propertys.temperature,//温度档位
      salt_add_time: propertys.salt_add_time,//盐疗定时初始值
      salt_timing: propertys.salt_timing,//盐疗定时
      salt_concentration: propertys.salt_concentration,//盐浓度
      oxygen_flow: propertys.oxygen_flow,//氧流量
      oxygen_concentration: propertys.oxygen_concentration,//氧浓度
      dark_mode: propertys.dark_mode, //夜间模式
      err_code: propertys.err_code,//异常状态码
      oxygen_dtime: propertys.oxygen_dtime,// 制氧定时
      oxtotal_time: propertys.oxtotal_time,//制氧累计时间
      oxygen_time: propertys.oxygen_time //制氧运行时间
    });

    // 运行状态
    // 如果运行状态0 改为默认参数
    if (that.data.dev_status == 0) {
      console.log("开关状态" + that.data.dev_status);
      // this.aliyun_default();
      that.setData({
        currentIndex: 0,
        buttonText: that.data.states[0],
        currentIndex_png: 0,
        buttonText_png: that.data.states_png[0],
        selected: null,
        show_usd: true,
        salt_button1: false,
        ox_button2: false,
        salt_canClick: true,
        ox_canClick: true,
        local_dev_status: '--'
      })


    }

    // 判断盐疗或

    if (that.data.dev_status == 1) {
      that.setData({
        currentIndex: 1,
        buttonText: that.data.states[1],
        currentIndex_png: 1,
        buttonText_png: that.data.states_png[1],
        local_dev_status: "待机",//手机端设备运行状态
        selected: null,
        show_usd: true,
        salt_button1: false,
        ox_button2: false,
        salt_canClick: true,
        ox_canClick: true,
      })
    }

    if (that.data.dev_status == 2 && that.data.salt_timing != 0) {
      console.log("盐疗开启");
      // 盐疗开启
      that.setData({
        currentIndex: 2,
        buttonText: that.data.states[2],
        currentIndex_png: 2,
        buttonText_png: that.data.states_png[2],
        local_dev_status: "运行",//手机端设备运行状态
        selected: 'salt',
        show_usd: true,
        salt_button1: true,
        ox_canClick: false

      })

    }

    if (that.data.dev_status == 3 && that.data.salt_timing != 0) {
      // 氧疗开启
      that.setData({
        currentIndex: 2,
        buttonText: that.data.states[2],
        currentIndex_png: 2,
        buttonText_png: that.data.states_png[2],
        local_dev_status: "运行",//手机端设备运行状态
        selected: 'oxygen',
        show_usd: false,
        ox_button2: true,
        salt_canClick: false
      })
      if (that.data.oxygen_dtime > that.data.oxygen_dtime_show) {
        that.setData({
          oxygen_dtime: '--',
        })
      }

    }

    // 夜间模式
    if (that.data.dark_mode == 1) {
      wx.showToast({
        title: '夜间模式已打开',
        image: '../img/night.png',
        duration: 2500,
        mask: true
      })
    }

    // 亮度档位
    if (that.data.screen_off == 0) {
      that.setData({
        currentLevel: that.data.levels[0] // 更新当前档位
      })
    } else {
      that.setData({
        currentLevel: that.data.levels[that.data.screen_off] // 更新当前档位
      })
    }

    // 如果出现报警，设备变成待机模式
    if (that.data.err_code == 0) {
      that.setData({
        err_code: 0 // 更新当前档位
      })
    } else {
      if (that.data.dev_status == 0) {
        // this.aliyun_default();
        // console.log("报警设备关机");
        that.setData({
          // currentIndex: 0,
          buttonText: that.data.states[0],
          // currentIndex_png: 0,
          // buttonText_png: that.data.states_png[0],
          // selected: null,
          // show_usd: true,
          // salt_button1: false,
          // ox_button2: false,
          // salt_canClick: true,
          // ox_canClick: true,
          err_code: 0,
          local_dev_status: '--'
        })
      } else {
        that.setData({
          currentIndex: 1,
          buttonText: that.data.states[1],
          currentIndex_png: 1,
          buttonText_png: that.data.states_png[1],
          // selected: null,
          // salt_button1: false,
          // ox_button2: false,
          // salt_canClick: true,
          // ox_canClick: true,
          // err_code: that.data.err_code,
          local_dev_status: "待机"
        })
      }


      aliSdk.request({
        Action: "SetDeviceProperty",
        ProductKey: that.data.product_type,
        DeviceName: that.data.deviceName,
        Items: "{dev_status:" + 1 + "}",
        Args: "" //无参服务，所以传空
      }, {
        method: "POST"
      },
        (res) => {

        })
    }

    // 盐疗时长结束，停止刷新数据，设备变成待机模式
    if (that.data.salt_timing == 0 && that.data.dev_status == 1) {
      that.setData({
        currentIndex: 1,
        buttonText: that.data.states[1],
        currentIndex_png: 1,
        buttonText_png: that.data.states_png[1],
        selected: null,
        local_dev_status: "待机",//手机端设备运行状态
        salt_button1: false,
        salt_canClick: true,
        ox_button2: false,
        ox_canClick: true

      })

      // aliSdk.request({
      //   Action: "SetDeviceProperty",
      //   ProductKey: that.data.product_type,
      //   DeviceName: that.data.deviceName,
      //   Items: "{dev_status:" + 1 + "}",
      //   Args: "" //无参服务，所以传空
      // }, {
      //   method: "POST"
      // },
      //   (res) => {
      //     this.onShow();
      //   })
    }


    // 盐疗时长结束，停止刷新数据，设备变成待机模式
    if (that.data.oxygen_dtime == 0 && that.data.dev_status == 1) {
      that.setData({
        currentIndex: 1,
        buttonText: that.data.states[1],
        currentIndex_png: 1,
        buttonText_png: that.data.states_png[1],
        selected: null,
        local_dev_status: "待机",//手机端设备运行状态
        salt_button1: false,
        salt_canClick: true,
        ox_button2: false,
        ox_canClick: true
      })
      // aliSdk.request({
      //   Action: "SetDeviceProperty",
      //   ProductKey: that.data.product_type,
      //   DeviceName: that.data.deviceName,
      //   Items: "{dev_status:" + 1 + "}",
      //   Args: "" //无参服务，所以传空
      // }, {
      //   method: "POST"
      // },
      //   (res) => {
      //     this.onShow();
      //   })
    }




  },

  select_model: function () {
    wx.showToast({
      title: '请选择模式',
      duration: 1500,
      mask: true,
      image: '../img/mode.png'
    });
  },
  /**
   * 浓度调节
   * @param {*} e 
   */
  salt_concentration_minus: function (e) {
    const that = this;
    that.stopAliyun();
    const salt_concentration_number = that.button_int_number(e.currentTarget.dataset.operation, that.data.salt_concentration, 1);
    if (that.data.dev_status != 0) {

      if (that.data.selected === 'salt') {

        // 获取最大可调物化时间
        if (salt_concentration_number >= 5 && salt_concentration_number <= that.data.salt_concentration_max) {
          that.setData({
            salt_concentration: salt_concentration_number
          });
          // 防抖处理：清除之前的定时器
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          // 设置新的定时器，3秒后更新最终值饿了
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{salt_concentration:" + salt_concentration_number + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 500); // 延迟1秒执行

        } else {
          this.onShow();
          wx.showModal({
            title: '提示',
            content: '调节范围在5到' + that.data.salt_concentration_max + '之间。',
            showCancel: false, // 不显示取消按钮
          });
        }
      } else {
        this.onShow();
        that.select_model();
      }
    } else {

      this.open_dev();
    }

  },

  /**
  * 盐疗-定时按钮 加 减
  */
  salt_timing_minus: function (e) {
    const that = this;
    that.stopAliyun();
    // 盐疗定时最大定时时长
    const powerSwitch = parseInt(that.data.powerSwitch);
    const salt_max = parseInt(that.data.salt_timing_max);
    // 页面显示盐疗定时
    // 界面值 +-5
    const salt_timing_result = that.button_int_number(e.currentTarget.dataset.operation, that.data.salt_timing, 1);
    // 盐疗定时初始值 +-5
    const salt_default_result = that.button_int_number(e.currentTarget.dataset.operation, that.data.salt_add_time, 1);
    that.setData({
      salt_add_time: salt_default_result
    });
    const salt_add_time = parseInt(that.data.salt_add_time);
    //判断定时时间  10<=盐疗定时（界面显示调节参数）<=最大定时时长
    if (that.data.dev_status == 0) {

      this.open_dev();
    } else {
      if (that.data.selected === 'salt') {

        if (that.data.dev_status == 1) {
          if (10 <= salt_timing_result && salt_timing_result <= salt_max) {
            // 设备待机或者运行
            that.setData({
              salt_timing: salt_timing_result
            });
            // 防抖处理：清除之前的定时器
            if (debounceTimer) {
              clearTimeout(debounceTimer);
            }
            // 设置新的定时器，3秒后更新最终值饿了
            debounceTimer = setTimeout(() => {
              aliSdk.request({
                Action: "SetDeviceProperty",
                ProductKey: that.data.product_type,
                DeviceName: that.data.deviceName,
                Items: "{salt_timing:" + salt_timing_result + "}",
                Args: "" //无参服务，所以传空
              }, {
                method: "POST"
              },
                (res) => {
                  this.onShow();
                })
            }, 500); // 延迟1秒执行

          } else {
            this.onShow();
            //判断定时时间  10<=盐疗定时（界面显示调节参数）<=最大定时时长
            wx.showModal({
              title: '提示',
              content: '调节范围在10到' + salt_max + '之间。',
              showCancel: false, // 不显示取消按钮
            });
          }
        }

        if (that.data.dev_status == 2) {
          // 盐疗定时初始值是<=最大时长
          //判断定时时间  10<=盐疗定时（界面显示调节参数）<=最大定时时长
          if (10 <= salt_timing_result && salt_timing_result <= salt_max) {
            if (salt_add_time >= 10 && salt_add_time <= salt_max) {
              // 设备待机或者运行
              that.setData({
                salt_timing: salt_timing_result
              });
              // 防抖处理：清除之前的定时器
              if (debounceTimer) {
                clearTimeout(debounceTimer);
              }
              // 设置新的定时器，3秒后更新最终值饿了
              debounceTimer = setTimeout(() => {
                aliSdk.request({
                  Action: "SetDeviceProperty",
                  ProductKey: that.data.product_type,
                  DeviceName: that.data.deviceName,
                  Items: "{salt_timing:" + salt_timing_result + "}",
                  Args: "" //无参服务，所以传空
                }, {
                  method: "POST"
                },
                  (res) => {
                    this.onShow();
                  })
              }, 500); // 延迟1秒执行

            } else {
              this.onShow();
              wx.showModal({
                title: '提示',
                content: '调节范围在10到' + salt_max + '之间。',
                showCancel: false, // 不显示取消按钮
              });
            }
          } else {
            this.onShow();
            wx.showModal({
              title: '提示',
              content: '调节范围在10到' + salt_max + '之间。',
              showCancel: false, // 不显示取消按钮
            });
          }
        }

      } else {
        this.onShow();
        that.select_model();
      }

    }


  },


  /**
  * 公用--开关机按钮
  */
  changeState: function () {
    const that = this;
    // 判断设备异常状态，若为异常，开关按钮设为1处于待机模式
    aliSdk.request({
      Action: "SetDeviceProperty",
      ProductKey: that.data.product_type,
      DeviceName: that.data.deviceName,
      Items: "{key_flag:" + 1 + "}",
      Args: "" //无参服务，所以传空
    }, {
      method: "POST"
    },
      (res) => {
        this.onShow();
        wx.showToast({
          title: '传输中...',
          duration: 3000,
          mask: true,
          image: '../img/send_aliyun.png'
        });
      })
  },


  /**
  * 公用--温度调节按钮 加 减
  */
  temperature_minus: function (e) {
    const that = this;
    that.stopAliyun();
    const temperature_result = that.button_int_number(e.currentTarget.dataset.operation, that.data.temperature, 1);
    if (that.data.dev_status != 0) {

      if (that.data.selected === 'salt') {
        if (temperature_result >= 1 && temperature_result <= 3) {
          that.setData({
            temperature: temperature_result
          });
          // 防抖处理：清除之前的定时器
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          // 设置新的定时器，3秒后更新最终值
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{temperature:" + temperature_result + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 500); // 延迟1秒执行
        } else {
          this.onShow();
          wx.showModal({
            title: '提示',
            content: '调节范围在1到3之间。',
            showCancel: false, // 不显示取消按钮
          });
        }
      } else {
        this.onShow();
        that.select_model();
      }
    } else {
      that.open_dev();
    }

  },

  /**
  * 公用--亮度档位调节
  * @param {*} e 
  */
  onLevelChange: function (e) {
    const that = this;
    that.stopAliyun();
    if (that.data.dev_status != 0) {
      if (that.data.selected === 'salt' || that.data.selected === 'oxygen') {
        that.setData({
          currentLevel: that.data.levels[e.detail.value] // 更新当前档位
        });
        // 防抖处理：清除之前的定时器
        if (debounceTimer) {
          clearTimeout(debounceTimer);
        }
        // 设置新的定时器，3秒后更新最终值
        debounceTimer = setTimeout(() => {
          aliSdk.request({
            Action: "SetDeviceProperty",
            ProductKey: that.data.product_type,
            DeviceName: that.data.deviceName,
            Items: "{screen_off:" + e.detail.value + "}",
            Args: "" //无参服务，所以传空
          }, {
            method: "POST"
          },
            (res) => {
              this.onShow();
            })
        }, 500); // 延迟1秒执行
      } else {
        this.onShow();
        that.select_model();
      }
    } else {

      this.open_dev();
    }
  },

  /**
   * 盐疗工作模式
   * @param {e}
   */
  salt_toggleTherapy: function (e) {
    const that = this;

    that.stopAliyun();
    const { salt_button1, ox_button2 } = that.data;

    // 设备是否处于开机或运行状态
    if (that.data.dev_status != 0) {
      // 防抖处理：清除之前的定时器
      if (debounceTimer) {
        clearTimeout(debounceTimer);
      }
      // 设置新的定时器，3秒后更新最终值
      debounceTimer = setTimeout(() => {
        if (salt_button1) {
          this.setData({
            salt_button1: false,
            ox_canClick: true,
            selected: null,
            currentIndex: 1,
            buttonText: that.data.states[1],
            currentIndex_png: 1,
            buttonText_png: that.data.states_png[1],
            mof_powewr: 1,
            show_usd: true
          });
          wx.showToast({
            title: '盐疗关闭',
            icon: 'loading',
            mask: true,
            duration: 1000
          })
          aliSdk.request({
            Action: "SetDeviceProperty",
            ProductKey: that.data.product_type,
            DeviceName: that.data.deviceName,
            Items: "{key_flag:" + 2 + "}",
            Args: "" //无参服务，所以传空
          }, {
            method: "POST"
          },
            (res) => {
              this.onShow();
            })

        } else if (!ox_button2) {

          that.setData({
            salt_button1: true,
            ox_canClick: false,
            selected: 'salt',
            currentIndex: 2,
            buttonText: that.data.states[2],
            currentIndex_png: 2,
            buttonText_png: that.data.states_png[2],
            show_usd: true
          });
          wx.showToast({
            title: '盐疗开启',
            mask: true,
            image: '../img/yl.png',
            duration: 1000
          })
          aliSdk.request({
            Action: "SetDeviceProperty",
            ProductKey: that.data.product_type,
            DeviceName: that.data.deviceName,
            Items: "{key_flag:" + 2 + "}",
            Args: "" //无参服务，所以传空
          }, {
            method: "POST"
          },
            (res) => {
              this.onShow();
            })
        }
      }, 500); // 延迟1秒执行

    } else {
      // 设备未打开
      this.open_dev();

    }

  },

  /**
 * 氧疗工作模式
 * @param {e}
 */
  ox_toggleTherapy: function (e) {
    const that = this;
    that.stopAliyun();
    const { salt_button1, ox_button2 } = that.data;
    // 设备是否处于开机或运行状态
    if (that.data.dev_status != 0) {
      // 防抖处理：清除之前的定时器
      if (debounceTimer) {
        clearTimeout(debounceTimer);
      }
      // 设置新的定时器，3秒后更新最终值
      debounceTimer = setTimeout(() => {
        if (ox_button2) {
          that.setData({
            ox_button2: false,
            salt_canClick: true,
            selected: null,
            currentIndex: 1,
            buttonText: that.data.states[1],
            currentIndex_png: 1,
            buttonText_png: that.data.states_png[1],
            mof_powewr: 1,
            show_usd: true
          });
          wx.showToast({
            title: '氧疗关闭',
            icon: 'loading',
            mask: true,
            duration: 1000
          })
          aliSdk.request({
            Action: "SetDeviceProperty",
            ProductKey: that.data.product_type,
            DeviceName: that.data.deviceName,
            Items: "{key_flag:" + 3 + "}",
            Args: "" //无参服务，所以传空
          }, {
            method: "POST"
          },
            (res) => {
              that.onShow();
            })
        } else if (!salt_button1) {
          that.setData({
            ox_button2: true,
            salt_canClick: false,
            selected: 'oxygen',
            currentIndex: 2,
            buttonText: that.data.states[2],
            currentIndex_png: 2,
            buttonText_png: that.data.states_png[2],
            show_usd: false
          });
          wx.showToast({
            title: '氧疗开启',
            image: '../img/ol.png',
            duration: 1000
          })
          aliSdk.request({
            Action: "SetDeviceProperty",
            ProductKey: that.data.product_type,
            DeviceName: that.data.deviceName,
            Items: "{key_flag:" + 3 + "}",
            Args: "" //无参服务，所以传空
          }, {
            method: "POST"
          },
            (res) => {
              that.onShow();
            })
        }
      }, 500); // 延迟1秒执行

    } else {
      // 设备未打开
      that.open_dev();
    }
  },

  /**
  * 氧流量按钮 加 减
  */
  oxygen_flow_minus: function (e) {
    const that = this;
    that.stopAliyun();
    const oxygen_flow__result = that.button_int_number(e.currentTarget.dataset.operation, that.data.oxygen_flow, 1);
    if (that.data.dev_status != 0) {
      if (that.data.selected === 'oxygen') {
        if (oxygen_flow__result >= 5 && oxygen_flow__result <= 50) {
          that.setData({
            oxygen_flow: oxygen_flow__result
          });
          // 防抖处理：清除之前的定时器
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{oxygen_flow:" + oxygen_flow__result + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 500); // 延迟1秒执行
        } else {
          this.onShow();
          wx.showModal({
            title: '提示',
            content: '调节范围在0.5到5之间。',
            showCancel: false, // 不显示取消按钮
          });
        }
      } else {
        this.onShow();
        that.select_model();
      }


    } else {
      that.open_dev();
    }

  },

  /**
  * 制氧定时按钮 加 减
  */
  oxygen_dtime_minus: function (e) {
    const that = this;
    that.stopAliyun();
    // 判断是加还是减
    const add_subtraction = parseInt(e.currentTarget.dataset.operation);
    // 设备是否开启
    if (that.data.dev_status != 0) {

      if (that.data.selected === 'oxygen') {
        // add_subtraction=1 减法 add_subtraction=2 加法

        if (add_subtraction == 1) {
          // 减后的值
          const oxygen_dtime_minus = that.button_int_number(parseInt(that.data.oxygen_dtime), 10, 3);
          // 判断最大点击次数是否为2 等于2就将盐疗定时设置成
          // 10 < 制氧定时 <= 最大值oxygen_dtime_show  步进10

          if (oxygen_dtime_minus >= 10 && oxygen_dtime_minus <= parseInt(that.data.oxygen_dtime_show)) {
            that.setData({
              oxygen_dtime: oxygen_dtime_minus
            });
          } else {

            wx.showToast({
              title: '连续运行模式',
              icon: 'loading',
              mask: true,
              duration: 1500
            });
            //制氧定时<=10 持续运行
            that.setData({
              oxygen_dtime: parseInt(that.data.oxygen_dtime_show) + 10
            });
          }
        } else {
          // add_subtraction=2 加法
          // 增加后的值

          const oxygen_dtime_add = that.button_int_number(parseInt(that.data.oxygen_dtime), 10, 1);

          console.log("增加后的" + oxygen_dtime_add);
          console.log("最大的" + that.data.oxygen_dtime_show);

          // 10 < 制氧定时 <= 最大值oxygen_dtime_show  步进10
          if (oxygen_dtime_add > 10 && oxygen_dtime_add <= parseInt(that.data.oxygen_dtime_show)) {
            that.setData({
              oxygen_dtime: oxygen_dtime_add
            });
          } else {
            if (oxygen_dtime_add < that.data.oxygen_dtime_show) {
              wx.showToast({
                title: '连续运行模式',
                icon: 'loading',
                mask: true,
                duration: 1500
              });
              //制氧定时<=10 持续运行
              that.setData({
                oxygen_dtime: parseInt(that.data.oxygen_dtime_show) + 1
              });
              console.log("****");
            } else {
              //制氧定时<=10 持续运行
              that.setData({
                oxygen_dtime: 10
              });
              console.log("-------");
            }

          }

        }
        // 防抖处理：清除之前的定时器
        if (debounceTimer) {
          clearTimeout(debounceTimer);
        }
        debounceTimer = setTimeout(() => {
          aliSdk.request({
            Action: "SetDeviceProperty",
            ProductKey: that.data.product_type,
            DeviceName: that.data.deviceName,
            Items: "{oxygen_dtime:" + that.data.oxygen_dtime + "}",
            Args: "" //无参服务，所以传空
          }, {
            method: "POST"
          },
            (res) => {
              this.onShow();
            })
        }, 500); // 延迟1秒执行


      } else {
        this.onShow();
        that.select_model();
      }

    } else {
      that.open_dev();
    }

  },

  /**
     * 处理减小按钮点击
     */
  handleDecrease() {
    const that = this;
    that.stopAliyun();
    that.stopApiCall();
    // 设备是否开启
    if (that.data.dev_status != 0) {
      if (that.data.selected === 'oxygen') {

        const current = that.data.oxygen_dtime;

        // 情况1：当前是"--"，点击减小直接跳转到180
        if (current === '--') {
          that.setData({ oxygen_dtime: that.data.oxygen_dtime_show });
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{oxygen_dtime:" + that.data.oxygen_dtime_show + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 500); // 延迟1秒执行

          return;
        }

        // 情况2：当前是有效数值（数字类型）
        const num = Number(current);
        if (isNaN(num)) {
          // 防御性编程：无效数值时重置为180（根据需求可调整）
          that.setData({ oxygen_dtime: that.data.oxygen_dtime_show });
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{oxygen_dtime:" + that.data.oxygen_dtime_show + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 500); // 延迟1秒执行
          return;
        }

        if (num <= 10) {
          wx.showToast({
            title: '连续运行模式',
            icon: 'loading',
            mask: true,
            duration: 1500
          });
          // 边界值10，点击减小变为--
          // const str = parseInt(that.data.oxygen_dtime_show) + 10;
          that.setData({ oxygen_dtime: '--' });
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{oxygen_dtime:" + 490 + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 500); // 延迟1秒执行
        } else {
          // 中间值，正常减10（如20→10，170→160）
          const newNum = num - 10;
          that.setData({ oxygen_dtime: newNum });
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{oxygen_dtime:" + newNum + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 500); // 延迟1秒执行
        }

      } else {
        this.onShow();
        that.select_model();
      }
    } else {
      that.open_dev();
    }
  },

  /**
   * 处理增加按钮点击
   */
  handleIncrease() {
    const that = this;
    that.stopAliyun();
    that.stopApiCall();
    // 设备是否开启
    if (that.data.dev_status != 0) {
      if (that.data.selected === 'oxygen') {

        const current = that.data.oxygen_dtime;

        // 情况1：当前是"--"，点击增加直接跳转到10
        if (current === '--') {
          that.setData({ oxygen_dtime: 10 });
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{oxygen_dtime:" + 10 + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 500); // 延迟1秒执行
          return;
        }

        // 情况2：当前是有效数值（数字类型）
        const num = Number(current);
        if (isNaN(num)) {
          // 防御性编程：无效数值时重置为10（根据需求可调整）
          that.setData({ oxygen_dtime: 10 });
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{oxygen_dtime:" + 10 + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 500); // 延迟1秒执行
          return;
        }
        if (num + 5 > that.data.oxygen_dtime_show) {
          wx.showToast({
            title: '连续运行模式',
            icon: 'loading',
            mask: true,
            duration: 1500
          });
          // 边界值180，点击增加变为--
          // const str = parseInt(that.data.oxygen_dtime_show) + 10;
          that.setData({ oxygen_dtime: '--' });
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{oxygen_dtime:" + 490 + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 500); // 延迟1秒执行
        } else {
          // 中间值，正常加10（如10→20，170→180）
          const newNum = num + 10;
          that.setData({ oxygen_dtime: newNum });
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{oxygen_dtime:" + newNum + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 500); // 延迟1秒执行
        }
      } else {
        this.onShow();
        that.select_model();
      }
    } else {
      that.open_dev();
    }
  },



  /**
   * 将返回结果转成key,value的json格式方便使用
   * @param {*} infos
   */
  convertPropertyStatusInfo: function (infos) {
    var data = {}
    infos.forEach((item) => {
      data[item.Identifier] = item.Value ? item.Value : null
    })
    return data;
  },

  /**
   * 请绑定设备按钮
   */
  jump: function () {
    wx.switchTab({
      url: '/pages/user/user' // 跳转到主页
    });
  }



})